package cn.itcast.web.controller.cargo;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.util.ImageUploadUtils;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/cargo/contractProduct", name = "货物管理")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list", name = "货物分页查询")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       String contractId) {

        // a查询货物分页对象
        // 1.创建货物查询对象
        ContractProductExample contractProductExample = new ContractProductExample();
        // 2.创建货物条件对象
        ContractProductExample.Criteria productExampleCriteria = contractProductExample.createCriteria();
        // 3.指定合同作为id条件
        productExampleCriteria.andContractIdEqualTo(contractId);
        // 4.分页查询
        PageInfo page = contractProductService.findByPage(pageNum, pageSize, contractProductExample);
        request.setAttribute("page", page);

        // b查询货物生产厂家
        // 1.创建厂家查询对象
        FactoryExample factoryExample = new FactoryExample();
        // 2.创建厂家条件对象
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        // 3.指定厂家类型条件
        factoryExampleCriteria.andCtypeEqualTo("货物");
        // 5.查询厂家列表
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        // c返回合同id
        request.setAttribute("contractId", contractId);

        return "cargo/product/product-list";
    }

    @RequestMapping(value = "/edit", name = "新增或修改")
    public String edit(ContractProduct cp, MultipartFile productPhoto) throws Exception {

        // 图片上传 start
        // 非空判断
        if (productPhoto != null && !productPhoto.isEmpty()) {
            // 调用七牛云工具类实现文件上传
            String imgUrl = ImageUploadUtils.upload(productPhoto.getInputStream());
            cp.setProductImage(imgUrl);
        }

        // 图片上传 end

        if (StrUtil.hasEmpty(cp.getId())) {
            // 设置货物 企业id、企业名称、创建人id、创建人部门id、创建时间
            cp.setCompanyId(getCompanyId());
            cp.setCompanyName(getCompanyName());
            cp.setCreateBy(getLoginUser().getId());
            cp.setCreateDept(getLoginUser().getDeptId());
            cp.setCreateTime(new Date());
            contractProductService.save(cp);
        } else {
            cp.setUpdateBy(getLoginUser().getId());
            cp.setUpdateTime(new Date());
            contractProductService.update(cp);
        }

        return "redirect:/cargo/contractProduct/list.do?contractId=" + cp.getContractId();
    }

    @RequestMapping(value = "/toUpdate", name = "去修改页面")
    public String toUpdate(String id) {

        // a根据货物id查询货物对象
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);

        // b查询货物生产厂家
        // 1.创建厂家查询对象
        FactoryExample factoryExample = new FactoryExample();
        // 2.创建厂家条件对象
        FactoryExample.Criteria factoryExampleCriteria = factoryExample.createCriteria();
        // 3.指定厂家类型条件
        factoryExampleCriteria.andCtypeEqualTo("货物");
        // 5.查询厂家列表
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        return "cargo/product/product-update";
    }

    /**
     * @param id         货物
     * @param contractId 合同
     */
    @RequestMapping(value = "/delete", name = "删除")
    public String delete(String id, String contractId) {

        contractProductService.delete(id);

        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    @RequestMapping(value = "/toImport", name = "进入货物批量上传页面")
    public String toImport(String contractId) {

        request.setAttribute("contractId", contractId);
        return "cargo/product/product-import";
    }

   /* @RequestMapping(value = "/importExcel", name = "货物批量上传")
    public String importExcel(String contractId, MultipartFile file) throws Exception {

        // i.解析excel封装到 List<ContractProduct>
        List<ContractProduct> list =  new ArrayList<>();
        // 1.加载上传excel文件
        Workbook wb = new XSSFWorkbook(file.getInputStream());
        // 2.读取第一页
        Sheet sheet = wb.getSheetAt(0);
        // 3.遍历行
        for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
            // 4.获取行对象 Row  == > ContractProduct 对象
            Row row = sheet.getRow(i);
            ContractProduct cp = new ContractProduct();
            // 5.获取单元格数据封装到对象属性中
            cp.setFactoryName(row.getCell(0).toString());
            cp.setProductNo(row.getCell(1).toString());
            cp.setCnumber((int)row.getCell(2).getNumericCellValue());
            cp.setPackingUnit(row.getCell(3).toString());
            cp.setLoadingRate(row.getCell(4).toString());
            cp.setBoxNum((int)row.getCell(5).getNumericCellValue());
            cp.setPrice(Double.parseDouble(row.getCell(6).toString()));
            cp.setProductDesc(row.getCell(7).toString());
            cp.setProductRequest(row.getCell(8).toString());
            // 6.设置合同id、企业id、企业名称、创建人id、创建人部门id
            cp.setContractId(contractId);
            cp.setCompanyId(getCompanyId());
            cp.setCompanyName(getCompanyName());
            cp.setCreateBy(getLoginUser().getId());
            cp.setCreateDept(getLoginUser().getDeptId());
            cp.setCreateTime(new Date());
            list.add(cp);
        }
        // ii.调用service保存货物对象
        for (ContractProduct contractProduct : list) {
            contractProductService.save(contractProduct);
        }

        return "redirect:/cargo/contract/list.do";
    }*/

    @RequestMapping(value = "/importExcel", name = "货物批量上传")
    public String importExcel(String contractId, MultipartFile file) throws Exception {

        // 1.使用easyPOI工具类完成批量导入
        List<ContractProduct> list = ExcelImportUtil.importExcel(file.getInputStream(), ContractProduct.class, new ImportParams());
        for (ContractProduct cp : list) {
            cp.setContractId(contractId);
            cp.setCompanyId(getCompanyId());
            cp.setCompanyName(getCompanyName());
            cp.setCreateBy(getLoginUser().getId());
            cp.setCreateDept(getLoginUser().getDeptId());
            cp.setCreateTime(new Date());
            contractProductService.save(cp);
        }

        return "redirect:/cargo/contract/list.do";
    }
}
